<template>
	<gracePage :customHeader="false">
		<!-- 页面主体 -->
		<view slot="gBody" class="grace-body">
			<view class="marginTop">
				<image src="https://static.graceui.com/graceui/logo201908.png" mode="widthFix" class="logo"></image>
			</view>
			<form @submit="loginNow" class="grace-form" style="margin-top:80rpx;">
				<view class="grace-form-item grace-border-b">
					<view class="grace-pnper">
						<picker :value="pnpre" @change="changePre" :range="pnpres" name="pn_pre" style="text-align:left;">
							<text class="grace-text">+{{pnpres[pnpre]}}</text><text class="grace-text grace-icons icon-arrow-down" style="margin-left:10rpx;"></text>
						</picker>
					</view>
					<view class="grace-form-body">
						<input type="number" v-model="phoneno" class="grace-form-input" name="pn" placeholder="请输入手机号码" />
					</view>
				</view>
				<view class="grace-form-item">
					<text class="grace-form-label">短信验证码</text>
					<view class="grace-form-body">
						<input type="number" class="grace-form-input" name="yzm" placeholder="请输入验证码" />
					</view>
					<view class="login-sendmsg-btn grace-bg-blue grace-border-radius" @tap="getVCode">{{vcodeBtnName}}</view>
				</view>
				<view class="grace-margin-top">
					<button form-type="submit" type="primary" class="grace-button grace-border-radius grace-gtbg-blue">
						登录 <text class="grace-icons icon-arrow-right"></text>
					</button>
				</view>
			</form>
		</view>
	</gracePage>
</template>
<script>
import gracePage from "../../graceUI/components/gracePage.vue";
var graceChecker = require("../../graceUI/jsTools/graceChecker.js");
var _self; 
export default {
	data() {
		return {
			token : "",
			pnpre : 0,
			pnpres : ['86', '01', '11', '26', '520'],
			vcodeBtnName: "获取验证码",
			countNum : 120,
			countDownTimer : null,
			phoneno : '',
			mCode : '',
			mCodeTemp : '',
			userInfoData:""
		}
	},
	onLoad: async function(){
		_self = this;
		_self.token =  await _self.$myFunction.getToken();
		_self.token = _self.token.token;
		_self.mCodeTemp = _self.$myFunction.rndNum(6);
	},
	methods:{
		changePre : function(e){
			this.pnpre = e.detail.value;
		},
		loginNow : function(e){
			// 表单验证
			var rule = [
				{ name: "pn", checkType: "phoneno", errorMsg: "请填写正确的手机号" },
				{ name: "yzm", checkType: "string", checkRule: "4,6", errorMsg: "请正确填写短信验证码" },
			];
			var formData = e.detail.value;
			var checkRes = graceChecker.check(formData, rule);
			// 验证通过
			if (checkRes) {
				//本机环境无需发送验证码
				if(_self.$myFunction.appConfig().environment == 'localhost'){
					// 验证通过
					// 销毁验证码
					_self.mCode = _self.$myFunction.rndNum(6);
					_self.mCodeTemp = _self.$myFunction.rndNum(6);
					//登录或注册
					_self.userSubmit();
				}else{
					if(formData.yzm == _self.mCodeTemp){
						// 验证通过
						// 销毁验证码
						_self.mCode = _self.$myFunction.rndNum(6);
						_self.mCodeTemp = _self.$myFunction.rndNum(6);
						//登录或注册
						_self.userSubmit();
					}else{
						uni.showToast({ title: '验证码错误', icon : "none"});
						return false;
					}
				}				
			} else {
				uni.showToast({ title: graceChecker.error, icon: "none" });
			}
		},
		getVCode : function(){
			var myreg=/^[1][0-9]{10}$/;
			if (!myreg.test(this.phoneno)){
				uni.showToast({ title: '请正确填写手机号码', icon : "none"});
				return false;
			}
			// 手机号码为 :  this.phoneno
			// vcodeBtnName 可以阻止按钮被多次点击 多次发送 return 会终止函数继续运行
			if (this.vcodeBtnName != '获取验证码' && this.vcodeBtnName != '重新发送'){return ;}
			this.vcodeBtnName =  "发送中...";
			// 与后端 api 交互，发送验证码 【自己写的具体业务代码】
			this.mCode = _self.$myFunction.rndNum(4);
			_self.mCodeTemp = this.mCode;
			_self.getMessage();
		},
		countDown : function(){
			if (this.countNum < 1){
			  clearInterval(this.countDownTimer);
			  this.vcodeBtnName = "重新发送";
			  return ;
			}
			this.countNum--;
			this.vcodeBtnName =  this.countNum + '秒重发';
		},
		//发送验证码
		getMessage: function(){
			uni.showToast({
				title: '请稍后...',
				duration:_self.$myFunction.appConfig().requestWaitTime,
				icon: 'none',
			});
			var params = {
				'mCode':_self.mCode,
				'phone':_self.phoneno
			};
			var paramsData = {
				"jsonParas":_self.$AesUtil.encrypt(encodeURIComponent(JSON.stringify(params)))
			}
			//重新获取一次token，防止接口返回认证失败系统重新获取的token未被使用
			_self.token = _self.$myFunction.appStorage('wuLuToken').token;
			uni.request({
				url:  _self.$myFunction.appConfig().serverAddress+'sendSms/siJiWuZhe/verifyCode',
				data: paramsData,
				method : "POST",
				header : {
					'content-type':'application/x-www-form-urlencoded',
					'Authentication':_self.token
				},		
				success: data => {
					// 刷新完毕后关闭刷新
					uni.hideToast();
					uni.stopPullDownRefresh();
					_self.$myFunction.displayLog("服务器返回数据："+JSON.stringify(data));					
					if (data.data.code == 200) {
						// 假设发送成功，给用户提示
						uni.showToast({ title: '短信已发送，请注意查收', icon : "none"});
						// 倒计时
						_self.countNum = 120;
						_self.countDownTimer = setInterval(function(){_self.countDown();}.bind(this), 1000);
					}else{
						//如果请求数据因token认证失败，则清空缓存token
						if(data.data.message.indexOf("接口访问未认证") != -1){
							uni.setStorage({
								key: 'wuLuToken',
								data: "",
								success: function () {	
									_self.$myFunction.displayLog("清空缓存token");
									//触发重新获取token
									_self.$myFunction.getToken();
									// 关闭所有页面，打开到应用内的某个页面。
									_self.$myFunction.displayLog("重加载当前页面");
									//返回首页，防止登场成功后再次进入登录界面
									uni.reLaunch({
										url: '/pages/object/index'
									});
								}
							});
							clearInterval(this.countDownTimer);
							_self.vcodeBtnName =  "获取验证码";
						}else{
							_self.$myFunction.displayLog("短信发送失败："+JSON.stringify(data));
							uni.showToast({title: '连接失败...',icon: 'none'});
							clearInterval(this.countDownTimer);
							_self.vcodeBtnName =  "获取验证码";
						}	
					}
				},
				fail: (data, code) => {
					uni.hideToast();
					uni.showToast({title: '连接失败...',icon: 'none'});
					clearInterval(this.countDownTimer);
					_self.vcodeBtnName =  "获取验证码";
				}
			});
		},
		userSubmit: function() {
			//用户注册
			//后台只需字段field2即可判断用户是否存在
			var params = {
				'field1':'油箱卫士',
				'field2':_self.phoneno,
				'field3':'',
				'field4':'',
				'field5':'',
				'field6':'',
				'field7':'',
				'field8':'',
				'field9':'',
				'field10':'',
				'field11':'',
				'field12':'',
				'field13':'',
				'field14':'',
				'field15':'',
				'field16':'',
				'field17':'油箱卫士',
				'field18':'',
				'field19':'',
				'field20':'',
				'field21':'',
				'status':"1"
			};
			var paramsData = {
				"jsonParas":_self.$AesUtil.encrypt(encodeURIComponent(JSON.stringify(params)))
			}
			//重新获取一次token，防止接口返回认证失败系统重新获取的token未被使用
			_self.token = _self.$myFunction.appStorage('wuLuToken').token;
			uni.showToast({
				title: '请稍后...',
				duration:_self.$myFunction.appConfig().requestWaitTime,
				icon: 'none',
			});
			uni.request({
				url: _self.$myFunction.appConfig().serverAddress + 'normalUserCreate',
				data: paramsData,
				method: "POST",
				header: {
					'content-type': 'application/x-www-form-urlencoded',
					'Authentication': _self.token
				},
				success: data => {
					uni.hideToast();
					_self.$myFunction.displayLog("用户注册服务器返回数据：" + JSON.stringify(data));
					let toastTitle, toastIcon, resType;
					if (data.data.code == 200) {
						resType = 0;
						toastIcon = 'success';
						toastTitle = '登录成功';
						uni.showToast({
							title: toastTitle,
							icon: toastIcon
						});
						_self.userInfoData = data.data.data;
						// 销毁验证码
						_self.mCode = _self.$myFunction.rndNum(6);
						_self.mCodeTemp = _self.$myFunction.rndNum(6);
						
						clearInterval(this.countDownTimer);
						_self.vcodeBtnName = "获取验证码";
						_self.logining = true;
						// _self.$myFunction.displayLog("登录成功，缓存用户数据：" + JSON.stringify(_self.userInfoData));
						//缓存数据
						uni.setStorage({
							key: 'wuLuUserInfo',
							data: _self.userInfoData,
							success: function() {
								uni.$emit('loginRefresh', {
									msg: '页面刷新'
								});
								setTimeout(function () {
									uni.navigateBack();
								}, 1500);
							}
						});
						
					}else{
						//如果请求数据因token认证失败，则清空缓存token
						if(data.data.message.indexOf("接口访问未认证") != -1){
							uni.setStorage({
								key: 'wuLuToken',
								data: "",
								success: function () {	
									_self.$myFunction.displayLog("清空缓存token");
									//触发重新获取token
									_self.$myFunction.getToken();
									// 关闭所有页面，打开到应用内的某个页面。
									_self.$myFunction.displayLog("重加载当前页面");
									//返回首页，防止登场成功后再次进入登录界面
									uni.reLaunch({
										url: '/pages/hardware/index'
									});
								}
							});
						}else{
							_self.$myFunction.displayLog("需求列表读取失败："+JSON.stringify(data));
							uni.showToast({title: '连接失败...',icon: 'none'});
						}	
					};
				},
				fail: (data, code) => {
					uni.showToast({title: '连接失败...',icon: 'none'});
				}
			});
		}
	},
	components:{
		gracePage
	}
}
</script>
<style>
.marginTop{margin-top:100rpx;}
.logo{width:250rpx; height:68rpx}
.login-sendmsg-btn{height:60rpx; width:200rpx; flex-shrink:0; margin-left:30rpx; text-align:center; background-color:#3688FF; line-height:60rpx; font-size:26rpx;}
.grace-pnper{width:168rpx; flex-shrink:0;}
.grace-form-label{width:168rpx;}
.grace-form-input{text-align:left;}
.grace-form-item{padding:10rpx 0;}
.grace-login-three-items{display:block; width:88rpx; height:88rpx; line-height:88rpx; font-size:60rpx; color:#3688FF; text-align:center; margin:10rpx;}
</style>